package com.cloud.animationtestdemo.utils

import android.view.View
import com.cloud.animationtestdemo.strage.BaseAnimationStrategy
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch

/**
 * @author: njb
 * @date:   2024/12/17 0:20
 * @desc:   常量工具类
 */
var animJob : Job?= null
object Constants {
    fun View.animateAlphaWithStrategy(
        duration: Long,
        strategy: BaseAnimationStrategy,
        startAlpha: Float = 1f,
        endAlpha: Float = 0f
    ) {
        val frameRate = 60L // 假设每秒60帧来更新动画
        val frameDuration = 1000 / frameRate

        // 使用flow来生成动画的每一帧数据
        val frameFlow: Flow<Int> = flow {
            val totalFrames = (duration / frameDuration).toInt()
            for (i in 0 until totalFrames) {
                emit(i)
            }
        }.flowOn(Dispatchers.Default)
        //取消协程
        animJob?.cancel()
        animJob = CoroutineScope(Dispatchers.Main).launch {
            frameFlow.collect { frame ->
                val progress = frame.toFloat() / (duration / frameDuration).toFloat()
                val alpha = startAlpha + (endAlpha - startAlpha) * strategy.getAlphaForProgress(progress)
                this@animateAlphaWithStrategy.animate().alpha(alpha).start()
                delay(frameDuration)
            }
        }
    }
}